package com.glink.manage.interceptor;

import com.glink.common.exception.GeneralSimpleException;
import com.glink.manage.common.CommonUtils;
import com.glink.manage.common.Constants;
import com.glink.manage.common.GrantCodeUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Objects;

/**
 * @author xum
 * @since 2025/2/18
 **/
@Slf4j
@Component
public class GrantCodeInterceptor implements HandlerInterceptor {

    @Value("${env.privateKey: R/xEKlitzBo61B2LNS6bMhTugW4lnYLlFfXX6dvkyYQ=}")
    private String privateKey;
//    @Value("${env.serialNumber:}")
//    private String serialNumber;
    
    @Value("${env.serialNumberUrl:http://192.168.1.31:1117/getSerialNumber}")
    private String serialNumberUrl;
    @Value("${env.grantCode:}")
    private String grantCode;
    
    @Value("${env.serialNumberDynamics:true}")
    private Boolean serialNumberDynamics;
    
    // 有效期
    public static Date periodValidity = null;

    
    @PostConstruct
    public void initGrantCode() throws GeneralSimpleException {
        log.info("--初始检查授权码开始--");
        periodValidity = GrantCodeUtil.periodValidity(privateKey, grantCode, getSerialNumber());
        log.info("--初始检查授权码结束--");
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String serialNumber = Constants.realTimeSerialNumber;
        if(StringUtils.isBlank(serialNumber)){
            serialNumber = getSerialNumber();
        }
        if(Objects.nonNull(periodValidity)){
            GrantCodeUtil.checkDateEfficacious(periodValidity, serialNumber);
        }else{
            periodValidity = GrantCodeUtil.periodValidity(privateKey, grantCode, serialNumber);
        }
       
        return true;
    }
    
    private String getSerialNumber(){
        String realTimeSerialNumber = "";
        if(serialNumberDynamics){
            try {
                realTimeSerialNumber = StringUtils.trim(CommonUtils.sendGet(serialNumberUrl));
            }catch (Exception e){
                log.error("系统序列号获取异常", e);
                throw new RuntimeException("系统序列号获取异常，请检查number服务有无启动！");     
            }
        }
        if(StringUtils.isBlank(realTimeSerialNumber)){
            throw new RuntimeException("系统序列号获取失败，请检查number服务有无启动！");
        }
        realTimeSerialNumber = StringUtils.trim(realTimeSerialNumber);
        if(StringUtils.isNotBlank(realTimeSerialNumber)){
            Constants.realTimeSerialNumber = realTimeSerialNumber;
        }
        return realTimeSerialNumber;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler,modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request,response,handler,ex);
    }
}
